<?php
/**
 * Created by PhpStorm.
 * User: kongqi
 * Date: 2019/10/4
 * Time: 13:16
 */

namespace App\Plugin\HostServer\Models;

use App\TraitClass\SearchScopeTrait;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Auth;

class PnHostSvUser extends Auth
{
    use SearchScopeTrait;
    use SoftDeletes;

    public $guarded = [];

    /**
     * 设置密码加密
     * @param $password
     */
    public function setPasswordAttribute($password)
    {
        if ($password) {
            $this->attributes['origin_password'] = $password;
            $this->attributes['password'] = bcrypt($password);

        }

    }

    public static function getType($field = '')
    {
        $type = [
            1 => '充值',
            2 => '购买',
            3 => '续费',
            4 => '提现',
            5 => '退款'
        ];
        return $field == '' ? $type : $type[$field];
    }

    /**
     * 取得会员
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(PnHostSvUser::class, 'user_id', 'id');
    }

    /**
     * 取得type 名字
     * @return array|mixed
     */
    public function getTypeNameAttributes()
    {
        return static::getType($this->type);
    }

    public static function regist($data)
    {

        $data = [
            'is_checked' => 1,
            'email' => $data['email'] ?? null,
            'password' => $data['password'] ?? null,
            'regist_ip' => \request()->getClientIp(),
            'buy_password' => $data['buy_password'],
            'name' => $data['name'] ?? null,
            'email_verified_at' => date('Y-m-d H:i:s')

        ];
        $u = self::create($data);

        if ($u) {

            return $u;
        } else {

            return false;
        }

    }

    /**
     * @param $user 充值会员
     * @param $money 充值金额
     * @param $model_id 来源模型id
     * @param $model_type 来源模型类型
     * @param string $str 来源说明
     * @return bool
     */
    public static function recharge($user,$money,$model_id,$model_type,$str='')
    {
        $before_money=$user['money'];
        $user->money=$user->money+$money;
        $r=$user->save();
        $user_money_data=[
            'user_id'=>$user['id'],
            'before_money'=>$before_money,
            'after_money'=>$user->money,
            'type'=>1,//充值
            'model_type'=>$model_type,
            'model_id'=>$model_id,
            'money'=>$money,
            'mark'=>$str.'充值'
        ];
        //会员变动表
        $mr=PnHostSvUserMoneyLog::add($user_money_data);
        if($mr && $r)
        {
            return true;
        }
        return false;
    }

    /**
     * 取得被锁会员
     * @param $id
     * @return mixed
     */
    public static function lockUser($id){
        return self::lockForUpdate()->find($id);
    }


}